package com.woniuxy.shiro;

import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: ideaAdmin
 * TODO: Class
 * TODO: 基于JWT的过滤器 JWT过滤器，拦截token信息
 * Date: 2022/2/23:12:00
 * Description:
 */

public class JWTFilter extends BasicHttpAuthenticationFilter {
    /**
        * TODO:这里一般都是用于统一后台跨域解决！后端跨域的代码不能有多个，只能用一套方案！
     *      *      前端处理了后端就可以不写！
    **/

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        //设置允许的请求方法
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        //设置请求头可以为跨域
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));

        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态

        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request,response);
    }

    /**
        * TODO: token的认证入口
     *          在这里判断token是登录认证还是授权
     *          在这里进行业务逻辑判断 和后续过滤器的调用
    **/
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //检查认证请求 获取请求头的token
        if(isLoginAttempt(request,response)){

            try {
                //执行登录方法 subject.login
                executeLogin(request,response);
            } catch (Exception e) {
                //如果请求头没有带Authorization属性的token 就到这里咯
                response401(request,response);
                e.printStackTrace();
            }
        }else {
            response401(request,response);
        }
        return true;
    }



    /**
        * TODO:登录请求判断 尝试获取请求头中Authorization的token信息
    **/
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        //获取请求头的Authorization的token
        String token = httpServletRequest.getHeader("Authorization");
        return token != null;
    }

    /**
        * TODO:真正的登录认证方法
    **/
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        //获取请求头的Authorization的token
        String token = httpServletRequest.getHeader("Authorization");

        //使用自定义实现类封装token
        getSubject(request,response).login(new MyJsonWebToken(token));

        return true;
    }

    /**
        * TODO:处理登录认证失败的请求 如果请求头没有token直接跳转到 /401的Controller
    **/
    private void response401(ServletRequest request, ServletResponse response) {
       // HttpServletResponse httpServletResponse = (HttpServletResponse) response;
       HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        try {
            httpServletRequest.getRequestDispatcher("/401").forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
